# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

import logging


class BookMap(object):
  def __init__(self, products, logger=None):
    self._logger = logger or logging.getLogger('BookMap')
    self._books = {product: None for product in products}
    self._timestamp = 0

  @property
  def timestamp(self):
    return self._timestamp

  def print_status(self):
    self._logger.info('Book status %d', self._timestamp)
    for product, book in self._books.items():
      print(product, book.timestamp, book.timestamp - self._timestamp)

  def get_book(self, product):
    return self._books[product]

  def set_book(self, product, book):
    self._timestamp = max(self._timestamp, book.timestamp)
    self._books[product] = book

  def is_book_ready(self, limit_ns=2e9):
    # Check the timestamp and every book is ready
    for book in self._books.values():
      if book is None or not book.has_ask() or not book.has_bid():
        return False

    min_ts = min(book.timestamp for book in self._books.values())
    if self._timestamp - min_ts > limit_ns:
      return False
    return True

  def is_book_sane(self):
    # Check the sanity of every book
    for product, book in self._books.items():
      if book is None:
        return False
      if (book.has_ask() and book.has_bid() and book.ask0().price <= book.bid0().price):
        self._logger.warn('Book for %s is insane: ask0(%f) <= bid0(%f)',
                          product,
                          book.ask0().price,
                          book.bid0().price)
        return False
    return True
